'use strict';
const errcode = require('../lib/errcode');
module.exports = () => {
    return async (ctx, next) => {
        ctx.__debug = [];
        ctx.ERRCODE = errcode;
        ctx.json = (data, code = 200) => {
            ctx.status = code;
            ctx.set('content-type', 'application/json');
            ctx.body = data;
        };
        ctx.error = (errcode, error, code = 500, message = 'server error') => {
            ctx.status = code;
            ctx.set('content-type', 'application/json');
            ctx.body = { errcode, error, message, debug: ctx.__debug };
        };
        ctx.fail = (errcode, fail, code = 400) => {
            ctx.status = code;
            ctx.set('content-type', 'application/json');
            ctx.body = { errcode, fail, debug: ctx.__debug };
        };
        ctx.debug = debug => {
            ctx.__debug.push(debug);
        };
        try {
            await next();
        } catch (e) {
            console.log(e);
            ctx.error(ctx.ERRCODE.SERVER_ERROR, e.message, 500);
        }
    };
};